<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="名称">
          <el-input v-model="searchInfo.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column align="left" label="图片">
          <template #default="scope">
            <img v-if="scope.row.cover" :src="scope.row.cover" style="width: 50px;height:50px;">
            <img v-else src="@/assets/noBody.png" style="width: 50px;height:50px;border-radius: 50%;">
          </template>
        </el-table-column>
        <el-table-column align="left" label="名称" prop="name" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" label="钓场" prop="groundName" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" label="钓塘" prop="pondName" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" label="玩法">
          <template #default="scope">
            {{ scope.row.play == 1 ? '按斤' : '按小时' }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="押金" prop="deposit" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" label="价格" prop="price" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="enterDialog">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="钓场" prop="groundId">
          <el-select v-model.number="form.groundId" placeholder="请选择" style="width: 500px" @change="selectDc">
            <el-option v-for="item in dcList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="钓塘" prop="pondId">
          <el-select v-model="form.pondId" placeholder="请选择" style="width: 500px">
            <el-option v-for="item in dtData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="重复">
          <el-select v-model="form.frequencys" placeholder="请选择" multiple style="width: 500px">
            <el-option v-for="item in repeatData.slice(1)" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="cover">
          <el-upload v-model:file-list="fileList1" :http-request="upload1" list-type="picture-card"
            :on-preview="handlePicturePreview">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="玩法" prop="play">
          <el-radio-group v-model.number="form.play" class="ml-4">
            <el-radio :value="1" size="large">按斤</el-radio>
            <el-radio :value="2" size="large">按小时</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开放时间" prop="open">
          <el-select v-model="form.open" placeholder="请选择" style="width: 500px">
            <el-option v-for="item in timeData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.open == 2" label="" v-for="(item, index) in form.timeList">
          <el-time-select v-model="item.startTime" style="width: 244px" :max-time="item.endTime" class="mr-4"
            placeholder="开始时间" start="08:00" step="00:60" end="19:00" />
          <el-time-select v-model="item.endTime" style="width: 244px" :min-time="item.startTime" placeholder="结束时间"
            start="08:00" step="00:60" end="19:00" />
          <el-icon :size="30" color="#3b82f6" style="cursor: pointer;margin-left: 8px;">
            <CirclePlus v-if="index == 0" @click="addTime(index)" />
            <Remove v-else @click="delTime(index)" />
          </el-icon>
        </el-form-item>
        <el-form-item label="押金" prop="deposit">
          <el-input v-model.number="form.deposit" placeholder="请输入" style="width: 500px;" /><span
            style="margin-left: 8px;">元</span>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="form.price" placeholder="请输入" style="width: 500px;" /><span
            style="margin-left: 8px;">元</span>
        </el-form-item>
        <el-form-item label="会员价格">
          <el-select v-model.number="form.vipPrice" placeholder="请选择" style="width: 280px;margin-right: 20px;">
            <el-option v-for="item in vipData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-input v-model.number="form.vipPrice" placeholder="请输入" style="width: 200px;" /><span
            style="margin-left: 8px;">元</span>
        </el-form-item>
        <el-form-item label="鱼获">
          <el-radio-group v-model.number="form.takeOut" class="ml-4">
            <el-radio :value="1" size="large">可带走</el-radio>
            <el-radio :value="2" size="large">不可带走</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分">
          <el-input v-model.number="form.points" placeholder="请输入" style="width: 500px;" /><span
            style="margin-left: 8px;">分</span>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  fishGroundsList,
  fishPondList,
  fileUpload,
  ticketList,
  ticketAdd,
  ticketEdit,
  verifyDelete,
  userVip
} from '@/api/diaochangguanli'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import AMapLoader from '@amap/amap-jsapi-loader'; //引入
import { CirclePlus, Remove } from '@element-plus/icons-vue'
// 通过该函数，可以获取组件当前所在的表单项formItem
const { formItem } = useFormItem()

defineOptions({
  name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
  name: '',
  open: '',
  play: 1,
  groundId: '',
  points: '',
  time: '',
  timeList: [
    {
      startTime: '',
      endTime: ''
    }
  ],
  takeOut: 1,
  type: 1,
  frequencys: [],
  frequency: '',
  vipPrice:''
})

const searchInfo = ref({
  name: ''
})

const userStore = useUserStore()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

function addTime(index) {
  let flag = form.value.timeList.some(item => !item.startTime || !item.endTime)
  if (flag) {
    ElMessage({
      type: 'info',
      message: '请填写时间'
    })
    return
  }
  form.value.timeList.push({
    startTime: '',
    endTime: ''
  })
}
function delTime(index) {
  form.value.timeList.splice(index, 1)
}
const repeatData = ref([
  {
    name: '不重复',
    id: 0
  },
  {
    name: '周一',
    id: 1
  },
  {
    name: '周二',
    id: 2
  },
  {
    name: '周三',
    id: 3
  },
  {
    name: '周四',
    id: 4
  },
  {
    name: '周五',
    id: 5
  },
  {
    name: '周六',
    id: 6
  },
  {
    name: '周日',
    id: 7
  }
])
const timeData = ref(
  [
    {
      name: '全天',
      id: 1
    },
    {
      name: '指定时间',
      id: 2
    },
  ]
)
let dialogVisible = ref(false)
let dialogImageUrl = ref()

//图片预览
const handlePicturePreview = (file, files) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true
}

const fileList1 = ref([])
function upload1(params) {
  fileUpload({ file: params.file }).then(res => {
    if (res.code == 200) {
      form.value.cover = res.result
      yyglForm.value.validateField('cover')
    } else {
      fileList1.value.pop()
    }
  })
}
let validate1 = (rule, value, callback) => {
  if (fileList1.value.length == 0) {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}
const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  groundId: [{ required: true, message: '请选择钓场', trigger: 'change' }],
  pondId: [{ required: true, message: '请选择钓塘', trigger: 'change' }],
  cover: [{ required: true, validator: validate1, trigger: 'change' }],
})

const yyglForm = ref(null)

const initForm = () => {
  yyglForm.value.resetFields()
  form.value = {
    name: '',
    open: '',
    play: 1,
    groundId: '',
    points: '',
    time: '',
    timeList: [
      {
        startTime: '',
        endTime: ''
      }
    ],
    takeOut: 1,
    type: 1,
    frequencys: [],
    frequency: '',
    vipPrice:''
  }
  fileList1.value=[]
}

const isEdit = ref(false)
const dialogTitle = ref('新增')
const addUnit = () => {
  dialogTitle.value = '新增'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const handleClose = (done) => {
  initForm()
  done()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await ticketList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result
    total.value = res.result.length
  }
}
getTableData()
const dcList = ref([])
const vipData = ref([])
onMounted(() => {
  fishGroundsList({ pageNumber: 1, pageSize: 100 }).then(res => {
    dcList.value = res.result
  })
  userVip().then(res=>{
    vipData.value = res.result
  })
})

const enterDialog = async () => {
  if (form.value.open == 2) {
    let flag = form.value.timeList.some(item => !item.startTime || !item.endTime)
    if (flag) {
      ElMessage({
        type: 'info',
        message: '请填写指定时间'
      })
      return
    }
  }
  yyglForm.value.validate(async (valid) => {
    if (valid) {
      console.log(form.value, 'form.value');
      form.value.frequency = form.value.frequencys.map(item => Number(item)).join(',')
      //form.value.deposit = Number(0.1)
      form.value.time = form.value.timeList.map(item => item.startTime + '-' + item.endTime).join(',')
      let res
      if (isEdit.value) {
        res = await ticketEdit(form.value)
      } else {
        res = await ticketAdd(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
        initForm()
        dialogFormVisible.value = false
      }
    }
  })
}

const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await verifyDelete(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const editUnit = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑'
  form.value = JSON.parse(JSON.stringify(row))
  form.value.ticketId = row.id
  if (form.value.cover) {
    fileList1.value.push({
      name: '1',
      url: form.value.cover
    })
  }
  getDtData(row.spotId)
  form.value.frequencys = form.value.frequency.split(',').map(item=>Number(item))
  console.log(form.value.frequencys,'form.value.frequencys')
  if (form.value.open == 2) {
    form.value.timeList = form.value.time.split(',').map(item => {
      return {
        startTime: item.split('-')[0],
        endTime: item.split('-')[1]
      }
    })
  }else{
    form.value.timeList= [{startTime:'',endTime:''}]
  }
  dialogFormVisible.value = true
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  page.value = 1
  searchInfo.value = {
    name: ''
  }
  getTableData()
}
function selectDc(val) {
  getDtData(val)
}
const dtData = ref([])
const getDtData = async (id) => {
  const res = await fishPondList({
    pageNumber: 1,
    pageSize: 100,
    groundsId: id
  })
  if (res.code == 200) {
    dtData.value = res.result.data
    //dtTotal.value = res.result.total
  }
}
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100%;
}
</style>
